package com.zzti.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DButil {

	private static String url = "jdbc:mysql://localhost:3306/homework?useUnicode=true&characterEncoding=utf8";
	private static String user = "root";
	private static String password = "123456";
	private static Connection connection;
	private static PreparedStatement ps;
	private static ResultSet rs;

	// 获取数据库连接
	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

	// 关闭数据库连接
	public static void closeAll() throws SQLException {
		if (rs != null) {
			rs.close();
		}
		if (ps != null) {
			ps.close();
		}
		if (connection != null) {
			connection.close();
		}
	}

	// 查询操作
	public static ResultSet select(String sql, Object[] obj) {
		connection = getConnection();
		try {
			ps = connection.prepareStatement(sql);
			if (null != obj) {
				for (int i = 0; i < obj.length; i++) {
					ps.setObject(i + 1, obj[i]);
				}
			}
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

	// 增删改操作
	public static int update(String sql, Object[] obj) {
		connection = getConnection();
		int a = 0;
		try {
			ps = connection.prepareStatement(sql);
			if (null != obj) {
				for (int i = 0; i < obj.length; i++) {
					ps.setObject(i + 1, obj[i]);
				}
			}
			a = ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return a;
	}
}
